<?php

class sms_model_annlog extends Model {
	public function __construct(){
		parent::__construct();
		$this->table = 'app_sms_announcement_log';
	}
	
	public function add($rows){
		$sql = "insert into ".$this->table." (uid, ann_id) values ";
		$rows = array_map("___annlog_map", $rows);
		$sql .= implode(",", $rows);
		$sql .= ' on DUPLICATE KEY UPDATE uid=uid';
		return $this->db->query($sql);
	}
	
	public function getUnread($uid){
		/*$sql = "SELECT count( a.id ) c
FROM app_sms_announcement a
LEFT JOIN app_sms_announcement_log l ON a.id = l.ann_id
WHERE (uid = $uid)
AND create_time>".(time()-604800);
		$c = $this->db->fetchField($sql, 'c');
		$sql = "select count(*) c from app_sms_announcement where create_time>".(time()-604800);*/
		//modify by fanzhanao@178.com
		$sql = 'select count(*) AS c from app_sms_announcement a where not EXISTS (select ann_id from app_sms_announcement_log b where uid='.$uid.' and a.id =b.ann_id ) AND a.create_time>'.(time()-604800);
		$c = $this->db->fetchField($sql, 'c');
		return $c;
	}
	
	public function getUnreadIds($uid){
		/*$sql = "SELECT a.id
FROM app_sms_announcement a
LEFT JOIN app_sms_announcement_log l ON a.id = l.ann_id
WHERE (uid = $uid)
AND create_time>".(time()-604800);
		$rows = $this->db->fetchAll($sql);		
		$sql = "select id from app_sms_announcement where create_time>".(time()-604800);*/
		//modify by fanzhanao@178.com
		$sql = 'select a.id from app_sms_announcement a where not EXISTS (select ann_id from app_sms_announcement_log b where uid='.$uid.' and a.id =b.ann_id ) AND a.create_time>'.(time()-604800);
		$rows = $this->db->fetchAll($sql);
		return $rows;
		//return array_udiff($rows2, $rows, '___annlog_compare_func');
	}
}

function ___annlog_map($a){
	return "(".$a['uid'].",".$a['ann_id'].")";
}

function ___annlog_compare_func($a, $b){
	if($a['id'] == $b['id']) return 0;
	return ($a['id']>$b['id'])?1:-1;
}